package com.eshop.web.intercepters;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eshop.common.util.security.Base64;
import com.eshop.common.util.security.MD5;
import com.google.gson.JsonObject;

public class APIIntercepter extends HandlerInterceptorAdapter {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	/**
	 * url结构是域名ueryString&key=base64(时间戳:||:MD5(queryString))
	 * 
	 * key的结构是queryString
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		double limit = 60L * 1000 * 2;//两分钟
//		// 访问的路径
//		String param = request.getQueryString();
//		String base = param.substring(0, param.lastIndexOf("&"));
//		String key = param.substring(param.lastIndexOf("&")+1, param.length());
//		String dkey = Base64.decodeURL(key);
//		String[] arr = dkey.split(":\\|\\|:");
//		JsonObject json = new JsonObject();
//		json.addProperty("success", false);
//		if(arr.length == 2&& MD5.getMD5(base).equals(arr[1])){
//			if((System.currentTimeMillis() - Long.parseLong(arr[0])) <= limit){
//					return true;
//			}else{
//				json.addProperty("msg", "请求超时");
//				json.addProperty("code", "-1");
//			}
//		}else{
//			json.addProperty("msg", "参数错误");
//			json.addProperty("code", "-2");
//		}
//		Writer out = response.getWriter();
//		out.write(json.toString());
//		out.flush();
//		out.close();
//		return false;
		return true;
	}
}
